package org.example;

import org.apache.lucene.analysis.core.SimpleAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.LongField;
import org.apache.lucene.document.TextField;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.SimpleFSDirectory;
import org.junit.Test;
import java.io.IOException;
import java.nio.file.Paths;

/**
 * @description: Lucene入门案例
 */
public class LuceneTest {

    //创建索引
    @Test
    public void createIndex() throws IOException {

        //模拟数据库的数据
        //第1行数据的两个字段
        Long id1 = 1L;
        String name1 = "hello world";
        //第2行数据的两个字段
        Long id2 = 2L;
        String name2 = "hello lucene";
        //第3行数据的两个字段
        Long id3 = 3L;
        String name3 = "oh my hello lucene elasticsearch";

        //1. 存放索引的目录
        Directory directory = new SimpleFSDirectory(Paths.get("E:\\lucene-demo\\index"));

        //2. 创建索引的相关配置(设置保存数据时，分词的方式) SimpleAnalyzer：简单的分词（一字一个词，一个单词一个词）
        IndexWriterConfig indexWriterConfig = new IndexWriterConfig(new SimpleAnalyzer());

        //3. 索引创建器
        IndexWriter indexWriter = new IndexWriter(directory, indexWriterConfig);

        //4. 开始数据封装
        Document document1 = new Document();
        //参数1：指定保存的字段名；参数2：保存字段对应的值；参数3：是否需要持久化存储
        document1.add(new LongField("id", id1, Field.Store.YES));
        document1.add(new TextField("name", name1, Field.Store.YES));

        Document document2 = new Document();
        document2.add(new LongField("id", id2, Field.Store.YES));
        document2.add(new TextField("name", name2, Field.Store.YES));

        Document document3 = new Document();
        document3.add(new LongField("id", id3, Field.Store.YES));
        document3.add(new TextField("name", name3, Field.Store.YES));

        //把文档添加到索引创建器
        indexWriter.addDocument(document1);
        indexWriter.addDocument(document2);
        indexWriter.addDocument(document3);

        //提交
        indexWriter.commit();
        indexWriter.close();
    }

}